package cn.ivicar.oss.controller;

import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.Customer;
import cn.com.carsmart.ws.model.CustomerVehicle;
import cn.com.carsmart.ws.model.Vehicle;
import cn.com.carsmart.ws.service.CustomerManager;
import cn.com.carsmart.ws.service.CustomerVehicleManager;
import cn.com.carsmart.ws.service.VehicleManager;
import cn.ivicar.oss.entity.ResponseEntity;
import cn.ivicar.oss.util.JsonUtils;
import com.google.inject.Inject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/5/16.
 */
public class CustomerController {

    @Inject
    private CustomerManager customerManager;
    @Inject
    private CustomerVehicleManager customerVehicleManager;
    @Inject
    private VehicleManager vehicleManager;

    public JSONObject getCustomerByMobile(String mobile) throws CarsmartException {
        if (StringUtils.isNotBlank(mobile)) {
            BaseExample example = this.customerManager.getExample();
            example.or().andPropertyEqualTo(mobile, "mobile");
            List<Customer> customers = this.customerManager.listByBaseExample(example);
            if (customers != null && customers.size() > 0) {
                JSONObject jsonObject = JsonUtils.getCustomerJSON(customers.get(0));
                return jsonObject;
            }
        }

        return null;
    }

    //分页待补充
    public JSONArray getCustomerList() throws CarsmartException {
        JSONArray jsonArray = new JSONArray();
        List<Customer> customers = this.customerManager.list();
        if (customers != null && customers.size() > 0) {
            for (Customer c : customers) {
                JSONObject jsonObject = JsonUtils.getCustomerJSON(c);
                jsonArray.add(jsonObject);
            }
        }

        return jsonArray;
    }

    public JSONObject getCustomerById(Long id) throws CarsmartException {
        BaseExample example = this.customerManager.getExample();
        example.or().andPropertyEqualTo(id, "id");
        List<Customer> customers = this.customerManager.listByBaseExample(example);
        if (customers != null && customers.size() > 0) {
            return JsonUtils.getCustomerJSON(customers.get(0));
        }

        return null;
    }

    public Long getVehicleIdByCId(Long customerId) throws CarsmartException {
        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(customerId, "customerId").andPropertyEqualTo(1, "status");
        List<CustomerVehicle> customerVehicles =
            this.customerVehicleManager.listByBaseExample(example);
        if (customerVehicles != null && customerVehicles.size() > 0) {
            return customerVehicles.get(0).getVehicleId();
        }

        return null;
    }

    public ResponseEntity updateCustomer(JSONObject obj) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (obj.isNullObject() || obj.isEmpty()) {
            responseEntity.setCode(400);
            responseEntity.setMessage("请求参数不能为空!");
            return responseEntity;
        }

        long customerId = obj.optLong("id");

        BaseExample example = this.customerManager.getExample();
        example.or().andPropertyEqualTo(customerId, "id");
        List<Customer> customers = this.customerManager.listByBaseExample(example);
        if (customers != null && customers.size() > 0) {
            Customer update = customers.get(0);
            if (obj.containsKey("mobile")) {
                String mobile = obj.optString("mobile", "").trim();
                if (mobile.length() != 11) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("手机号码长度不正确！");
                    return responseEntity;
                }
                update.setMobile(mobile);
            }

            if (obj.containsKey("email")) {
                String email = obj.optString("email", "").trim();
                update.setEmail(email);
            }

            if (obj.containsKey("nickName")) {
                String nickname = obj.optString("nickName", "").trim();
                if (nickname.length() > 6) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("昵称过长！不能超过6位！");
                    return responseEntity;
                }
                update.setNickname(nickname);
            }

            if (obj.containsKey("sex")) {
                String sexStr = obj.optString("sex", "男");//0 女 1 男
                if ("男".equalsIgnoreCase(sexStr)) {
                    update.setSex(String.valueOf(1));
                } else {
                    update.setSex(String.valueOf(0));
                }
            }
            this.customerManager.update(update);
            responseEntity.setDataObject(update);
            return responseEntity;
        }

        responseEntity.setCode(400);
        responseEntity.setMessage("更新失败！客户信息不存在！");
        return responseEntity;

    }

    public ResponseEntity deleteCustomer(String id) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (StringUtils.isBlank(id)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取用户标识!");
            return responseEntity;
        }

        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(Long.parseLong(id), "vehicleId")
            .andPropertyEqualTo(1, "status");
        int count = this.customerVehicleManager.countByExample(example);
        if (count > 0) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！请先解除人车关系！");
            return responseEntity;
        }
        this.customerManager.deleteByPrimaryKey(Long.parseLong(id));
        return responseEntity;
    }

    public ResponseEntity deleteVehicle(String cid,
        String vid) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (StringUtils.isBlank(cid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取用户标识!");
            return responseEntity;
        }
        if (StringUtils.isBlank(vid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取车辆标识!");
            return responseEntity;
        }

        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(Long.parseLong(vid), "vehicleId")
            .andPropertyEqualTo(Long.parseLong(cid), "customerId").andPropertyEqualTo(1, "status");
        List<CustomerVehicle> customerVehicles =
            this.customerVehicleManager.listByBaseExample(example);
        if (customerVehicles != null && customerVehicles.size() > 0) {
            CustomerVehicle customerVehicle = customerVehicles.get(0);
            customerVehicle.setStatus(0);
            this.customerVehicleManager.updateSelective(customerVehicle);
            return responseEntity;
        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！关系异常，未查询到关联关系!");
            return responseEntity;
        }
    }

    public JSONArray getVehicles(String id) throws CarsmartException {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(Long.parseLong(id), "customerId")
            .andPropertyEqualTo(1, "status");
        List<CustomerVehicle> customerVehicles =
            this.customerVehicleManager.listByBaseExample(example);
        if (customerVehicles != null && customerVehicles.size() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (CustomerVehicle cv : customerVehicles) {
                JSONObject vehicleObj = getVehicleById(cv.getVehicleId());
                if (vehicleObj != null) {
                    if (cv.getOwner()) {
                        vehicleObj.put("relation", "绑定关系");
                    } else {
                        vehicleObj.put("relation", "分享关系");
                    }
                    //增加绑定时间
                    Date create = cv.getCreated();
                    String createStr = sdf.format(create);
                    vehicleObj.put("bindTime",createStr);

                    jsonArray.add(vehicleObj);
                }
            }
        }

        return jsonArray;
    }

    public JSONObject getVehicleById(Long id) throws CarsmartException {

        BaseExample example = this.vehicleManager.getExample();
        example.or().andPropertyEqualTo(id, "id");
        List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
        if (vehicles != null && vehicles.size() > 0) {
            JSONObject vehicleJSON = JsonUtils.getVehicleJSON(vehicles.get(0));
            return vehicleJSON;
        }

        return null;
    }

    public ResponseEntity addVehicleRel(JSONObject jsonObject) throws CarsmartException {
        ResponseEntity responseEntity = new ResponseEntity();
        if (null == jsonObject) {
            responseEntity.setCode(400);
            responseEntity.setMessage("参数异常!对象为空！");
            return responseEntity;
        }
        String cid = jsonObject.getString("cid");
        if (StringUtils.isBlank(cid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("未获取客户标识!");
            return responseEntity;
        }
        String value = jsonObject.getString("value");
        if (StringUtils.isBlank(value)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("车辆信息不能为空!");
            return responseEntity;
        }
        String relaType = jsonObject.optString("relaType", "0");
        String type = jsonObject.optString("type", "2");
        BaseExample example = this.vehicleManager.getExample();
        BaseExample.Criteria or = example.or();
        if ("1".equalsIgnoreCase(type)) {
            //大驾号
            or.andPropertyEqualTo(value, "serial");
        } else {
            //车牌号
            or.andPropertyEqualTo(value, "licensePlate");
        }
        List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
        if (vehicles != null && vehicles.size() > 0) {
            Long id = vehicles.get(0).getId();
            //如果增加绑定关系，则先判断车辆是否已经存在绑定关系
            if ("1".equalsIgnoreCase(relaType)) {
                BaseExample example1 = this.customerVehicleManager.getExample();
                example1.or().andPropertyEqualTo(id, "vehicleId").andPropertyEqualTo(true, "owner")
                    .andPropertyEqualTo(1, "status");
                int i = this.customerVehicleManager.countByExample(example1);
                if (i > 0) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("绑定失败！该车辆已存在绑定关系!");
                    return responseEntity;
                }
            }

            //表中已经存在删除状态的人车关系，防止插入失败，更新状态
            BaseExample example1 = this.customerVehicleManager.getExample();
            example1.or().andPropertyEqualTo(id, "vehicleId")
                .andPropertyEqualTo(Long.parseLong(cid), "customerId");
            List<CustomerVehicle> customerVehicles =
                this.customerVehicleManager.listByBaseExample(example1);
            if (customerVehicles != null && customerVehicles.size() > 0) {
                CustomerVehicle customerVehicle = customerVehicles.get(0);
                customerVehicle.setStatus(1);
                customerVehicle.setOwner("1".equalsIgnoreCase(relaType) ? true : false);
                customerVehicle.setCreated(new Date());
                customerVehicle.setUpdated(new Date());
                this.customerVehicleManager.updateSelective(customerVehicle);
                return responseEntity;

            } else {

                CustomerVehicle customerVehicle = new CustomerVehicle();
                customerVehicle.setCustomerId(Long.valueOf(cid));
                customerVehicle.setVehicleId(id);
                customerVehicle.setStatus(1);
                customerVehicle.setOwner("1".equalsIgnoreCase(relaType) ? true : false);
                customerVehicle.setCreated(new Date());
                customerVehicle.setUpdated(new Date());
                try {
                    this.customerVehicleManager.insert(customerVehicle);
                    return responseEntity;
                } catch (Exception e) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("关系已存在，重复添加!");
                    return responseEntity;
                }
            }



        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("车辆不存在!");
            return responseEntity;
        }

    }


}
